package niu.fencer.tool.qrcode.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.android.material.bottomnavigation.BottomNavigationView;

import com.king.zxing.util.CodeUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import java.io.File;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import niu.fencer.tool.qrcode.R;
import niu.fencer.tool.qrcode.ui.FragmentFile;
import niu.fencer.tool.qrcode.ui.FragmentQuick;
import niu.fencer.tool.qrcode.ui.FragmentText;
import niu.fencer.tool.qrcode.util.ActivityUtils;
import niu.fencer.tool.qrcode.util.LogUtil;
import niu.fencer.tool.qrcode.util.UriUtils;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;


public class MainActivity extends AppCompatActivity  implements BottomNavigationView.OnNavigationItemSelectedListener, EasyPermissions.PermissionCallbacks{

    public static final String KEY_TITLE = "key_title";
    public static final String KEY_IS_QR_CODE = "key_code";
    public static final String KEY_IS_CONTINUOUS = "key_continuous_scan";

    public static final int REQUEST_CODE_SCAN = 0X01;
    public static final int REQUEST_CODE_PHOTO = 0X02;

    public static final int RC_CAMERA = 0X01;

    public static final int RC_READ_PHOTO = 0X02;

    public static final String IS_FILE ="Is_File";
    public static final String QRCODE_SOURCE = "QrCode_Source";
    public static final String IN_PRIVATE_DIR="private_data";

    ViewPager _viewPager;
    BottomNavigationView _bottomNav;
    SectionsPagerAdapter _viewPagerAdapter ;
    public Toolbar _toolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        _toolbar=findViewById(R.id.toolbar);


        _bottomNav = findViewById(R.id.nav_view);
        _bottomNav.setOnNavigationItemSelectedListener(this);

        _viewPager =findViewById(R.id.view_pager);
        _viewPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
        _viewPager.setAdapter(_viewPagerAdapter);

    }

    private void startScan(Class<?> cls,String title){
        Intent intent = new Intent(this, cls);
        intent.putExtra(KEY_TITLE,title);
        intent.putExtra(KEY_IS_CONTINUOUS,true);
        startActivityForResult(intent,REQUEST_CODE_SCAN);
    }
    /**
     * 检测拍摄权限
     */
    @AfterPermissionGranted(RC_CAMERA)
    private void checkCameraPermissions(){
        String[] perms = {Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {//有权限
            startScan(QrCodeRecActivity.class, "title111");
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, getString(R.string.permission_camera), RC_CAMERA, perms);
        }
    }
    private void startPhotoCode(){
        Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(pickIntent, REQUEST_CODE_PHOTO);
    }

    @AfterPermissionGranted(RC_READ_PHOTO)
    private void checkExternalStoragePermissions(){
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {//有权限
            startPhotoCode();
        }else{
            EasyPermissions.requestPermissions(this, getString(R.string.permission_external_storage),
                    RC_READ_PHOTO, perms);
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {


        if(data!=null)
        {
            String  filePath=data.getExtras().getString(MainActivity.QRCODE_SOURCE);
//            Toast.makeText(getBaseContext(),resultCode+"filePath:"+filePath+requestCode,Toast.LENGTH_SHORT).show();
            LogUtil.i(resultCode+"filePath:"+filePath+requestCode);
            switch (requestCode){
                case REQUEST_CODE_SCAN:
                    Bundle args = data.getExtras();
                    switchTab(R.id.navigation_text,args);
                    break;
                case REQUEST_CODE_PHOTO:
                    parsePhoto(data);
                    break;
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    private void asyncThread(Runnable runnable){ new Thread(runnable).start(); }
    private void parsePhoto(Intent data){
        final String path = UriUtils.getImagePath(this,data);
        Log.d("Jenly","path:" + path);
        if(TextUtils.isEmpty(path)){
            return;
        }
        //异步解析
        asyncThread(new Runnable() {
            @Override
            public void run() {
                final String result = CodeUtils.parseCode(path);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("Jenly","result:" + result);
                        Toast.makeText(getBaseContext(),result,Toast.LENGTH_SHORT).show();
                    }
                });

            }
        });

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_qrcode_scan: {
                checkCameraPermissions();
                break;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    public void switchTab(int menuItemId,Bundle args) {
        LogUtil.i("switchTab"+args!= null ? args.getString(MainActivity.QRCODE_SOURCE, "") : "");
        // Check index ...
        MenuItem item=_bottomNav.getMenu().findItem(menuItemId);
        if(item==null){
            return;
        }

        this.onNavigationItemSelected(item);
        _bottomNav.setSelectedItemId(item.getItemId());
        _viewPager.setSelected(true);
        int pageItem=_viewPager.getCurrentItem();
        LogUtil.i(pageItem+" "+_viewPagerAdapter.getCachedFragments());
        Fragment fragment=_viewPagerAdapter.getCachedFragments().get(pageItem);
        if(fragment instanceof FragmentText){
            ((FragmentText) fragment).switchToMe(args);
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.navigation_text: {
                _viewPager.setCurrentItem(0);
                return true;
            }
            case R.id.navigation_file:{
                _viewPager.setCurrentItem(1);
                return true;
            }
            case R.id.navigation_quick:{
                _viewPager.setCurrentItem(2);
                return true;
            }
        }
        return false;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
        // Some permissions have been granted

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {
        // Some permissions have been denied
        // ...
    }


    public class SectionsPagerAdapter extends FragmentPagerAdapter {
        private HashMap<Integer, Fragment> _fragCache = new LinkedHashMap<>();
        @StringRes
        private  final int[] TAB_TITLES = new int[]{R.string.title_text, R.string.title_file,R.string.title_quick};
        private final Context mContext;

        public SectionsPagerAdapter(Context context, FragmentManager fm) {
            super(fm);
            mContext = context;
        }

        @Override
        public Fragment getItem(int pos) {
            Fragment fragment = _fragCache.get(pos);
            if(fragment==null){
                switch (_bottomNav.getMenu().getItem(pos).getItemId()) {
                    case R.id.navigation_text: {
                        fragment=FragmentText.newInstance();
                        break;
                    }
                    case R.id.navigation_file:{
                        fragment= FragmentFile.newInstance();
                        break;

                    }
                    case R.id.navigation_quick:{
                        fragment= FragmentQuick.newInstance();
                        break;
                    }
                }
                _fragCache.put(pos, fragment);
            }
//            onNavigationItemSelected(_bottomNav.getMenu().getItem(pos));
//            _bottomNav.setSelectedItemId(_bottomNav.getMenu().getItem(pos).getItemId());
            return fragment;
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return mContext.getResources().getString(TAB_TITLES[position]);
        }

        @Override
        public int getCount() {
            return _bottomNav.getMenu().size();
        }
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            super.destroyItem(container, position, object);
            _fragCache.remove(position);
        }
        public HashMap<Integer, Fragment> getCachedFragments() {
            return _fragCache;
        }
    }
}